package readHandle

import (
	"chart.zozoo.net/app/dao/messageHistoryDao"
	"chart.zozoo.net/app/service/userService"
	"chart.zozoo.net/app/socket/connManage"
	"chart.zozoo.net/app/socket/writeHandle"
	"chart.zozoo.net/core/myRedis"
	"encoding/json"
	"fmt"
	"time"
)

type HistoryRsp struct {
	Uuid      string    `json:"f_uuid"`
	MsgView   string    `json:"msg_view"`
	UnreadNum int       `json:"unread_num"`
	CreatedAt time.Time `json:"created_at"`
}

// 获取用户聊天记录列表
func handleMessageHistory(msg string, addr string) {
	var err error

	//获取聊天记录
	connInfo := connManage.GetConn(addr)
	user := connInfo.UserInfo

	errMsg := ChatMessage{
		ToUid:      user.Uuid,
		MsgType:    "errMsg",
		MsgContent: "",
	}

	//获取用户缓存
	key := GetMessageHistoryCacheKey(user.Id)

	//获取缓存
	res := myRedis.RedisClient.HGetAll(key)
	if res.Err() != nil {
		errMsg.MsgContent = res.Err().Error()
		writeHandle.WriteMessage(connInfo.Conn, errMsg)
		fmt.Println(1)
		return
	}

	h := new(HistoryRsp)
	l := make([]HistoryRsp, 0)
	strMap := res.Val()
	if len(strMap) != 0 {
		//缓存存在
		for _, v := range strMap {
			//将字符串转为结构体
			err = json.Unmarshal([]byte(v), h)
			if err != nil {
				errMsg.MsgContent = res.Err().Error()
				writeHandle.WriteMessage(connInfo.Conn, errMsg)
				fmt.Println(3)
				return
			}
			l = append(l, *h)
		}
	} else {
		//查询数据库
		list, err := messageHistoryDao.Find(user.Id)
		if err != nil {
			errMsg.MsgContent = res.Err().Error()
			writeHandle.WriteMessage(connInfo.Conn, errMsg)
			return
		}
		for _, v := range list {
			u, err := userService.InfoByUuid(v.FUuid)
			if err != nil {
				errMsg.MsgContent = res.Err().Error()
				writeHandle.WriteMessage(connInfo.Conn, errMsg)
				return
			}

			l = append(l, HistoryRsp{
				Uuid:      u.Uuid,
				CreatedAt: v.CreatedAt,
				MsgView:   v.MsgView,
				UnreadNum: v.UnreadNum,
			})

			//添加缓存
			str, err := json.Marshal(v)
			if err != nil {
				errMsg.MsgContent = res.Err().Error()
				writeHandle.WriteMessage(connInfo.Conn, errMsg)
				return
			}
			myRedis.RedisClient.HSet(key, v.FUuid, string(str))
		}
	}

	//返回结果
	content, err := json.Marshal(l)
	if err != nil {
		errMsg.MsgContent = err.Error()
		writeHandle.WriteMessage(connInfo.Conn, errMsg)
		fmt.Println(4)
		return
	}
	errMsg.MsgType = "messageHistory"
	errMsg.MsgContent = string(content)
	writeHandle.WriteMessage(connInfo.Conn, errMsg)
}
